
from flask import Flask, render_template, request
import pandas as pd
import cufflinks as cf
import plotly as py
import plotly.graph_objs as go


app = Flask(__name__)


# @app.route('/search4', methods=['POST'])
# def do_search() -> 'html':
#     phrase = request.form['phrase']
#     letters = request.form['letters']
#     title = 'Here are your results:'
#     results = str(search4letters(phrase, letters))
#     return render_template('results.html',
#                            the_title=title,
#                            the_phrase=phrase,
#                            the_letters=letters,
#                            the_results=results,)
#

df = pd.read_csv('hurun.csv', encoding='utf-8', delimiter="\t")
regions_available = list(df.region.dropna().unique())
cf.set_config_file(offline=True, theme="ggplot")
py.offline.init_notebook_mode()
@app.route('/hurun',methods=['GET'])
def hu_run_2019():
    data_str = df.to_html()
    return render_template('results2.html',
                           the_res = data_str,
                           the_select_region=regions_available)

@app.route('/hurun',methods=['POST'])
def hu_run_select() -> 'html':
    the_region = request.form["the_region_selected"]
    print(the_region) # 检查用户输入
    dfs = df.query("region=='{}'".format(the_region))
    df_summary = dfs.groupby("行业").agg({"企业名称":"count","估值（亿人民币）":"sum","成立年份":"mean"}).sort_values(by = "企业名称",ascending = False )
    print(df_summary.head(5)) # 在后台检查描述性统计
    ## user select
    # print(dfs)
    # 交互式可视化画图
    fig = dfs.iplot(kind="bar", x="行业", y="估值（亿人民币）", asFigure=True)
    py.offline.plot(fig, filename="example.html",auto_open=False)
    with open("example.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    # plotly.offline.plot(data, filename='file.html')
    data_str = dfs.to_html()
    return render_template('results2.html',
                            the_plot_all = plot_all,
                            the_res = data_str,
                            the_select_region=regions_available,
                           )

@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html',
                           the_title='Welcome to search4letters on the web!')


if __name__ == '__main__':
    app.run(debug=True)
